package com.lagou.algorithmus;

import com.lagou.algorithmus.data.ListNode;

/**
 * 链表
 */
public class AlgorithmusLinkedNode {


    public static void main(String[] args) {
        int[] arr01 = {4,1,8,4,5};
        int[] arr02 = {5,6,1,8,4,5};
        ListNode headA = new ListNode(4);
        ListNode a01 = new ListNode(1);
        ListNode a02 = new ListNode(8);
        ListNode a03 = new ListNode(4);
        ListNode a04 = new ListNode(5);
        headA.next = a01;
        a01.next = a02;
        a02.next = a03;
        a03.next = a04;



        ListNode headB = new ListNode(5);
        ListNode b01 = new ListNode(6);
        ListNode b02 = new ListNode(1);
        ListNode b03 = new ListNode(8);
        ListNode b04 = new ListNode(4);
        ListNode b05 = new ListNode(5);

        headB.next = b01;
        b01.next = b02;
        b02.next = b03;
        b03.next = b04;
        b04.next = b05;

        AlgorithmusLinkedNode test = new AlgorithmusLinkedNode();
        System.out.println(test.getIntersectionNode(headA, headB).val);

    }


    /**
     * 给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点，返回 null 。
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
